const express = require("express");
const { User, getUserRoleMenu } = require("../models/role");
const token = require("../middleware/jwt");
const { AppUser } = require("../models/appUser");
module.exports = {
  // 测试中间件
  async test(req, res) {
    // admin才能访问
    // checkTokenAdmin(req, res, next)
    let { userId } = req;
    console.log(userId);
    res.send({
      data: userId,
    });
  },
  async init(req, res) {
    // 从token解析出用户id
    let userId = req.userId;
    if (!userId) {
      res.json({
        code: 400,
        message: "无权限",
        data: null,
      });
      return;
    }
    let data = await getUserRoleMenu(userId);
    res.json({
      code: 200,
      message: "初始化成功",
      data: data,
    });
  },

  async userLogin(req, res) {
    const { username, password } = req.body;
    // 查询数据库是否存在该用户
    AppUser.findOne({
      where: {
        username: username,
      },
    }).then((user) => {
      if (user) {
        // 比较密码
        if (user.password === password) {
          // 生成token
          const tokenStr = token.getTokenUser(user.id, user.name);
          res.json({
            code: 200,
            message: "登录成功",
            data: user,
            token: tokenStr,
          });
          return;
        } else {
          res.json({
            code: 400,
            message: "密码错误",
            data: null,
          });
          return;
        }
      } else {
        res.json({
          code: 400,
          message: "用户不存在",
          data: null,
        });
        return;
      }
    });
  },
  async userRegister(req, res) {
    const { name, username, password } = req.body;
    // 查询数据库是否存在该用户
    AppUser.findOne({
      where: {
        username: username,
      },
    }).then((user) => {
      if (user) {
        res.json({
          code: 400,
          message: "用户已存在",
          data: null,
        });
        return;
      } else {
        AppUser.create({
          name: name,
          username: username,
          password: password,
        }).then((user) => {
          res.json({
            code: 200,
            message: "注册成功",
            data: user,
          });
          return;
        });
      }
    });
  },
};
